package com.hzw.saas.web.storage.security;

import com.hzw.saas.api.user.IUserAccountService;
import com.hzw.saas.api.user.bo.UserAccountBO;
import com.hzw.saas.common.security.pojo.dto.SaasUser;
import lombok.AllArgsConstructor;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.ArrayList;
import java.util.Map;
@AllArgsConstructor
public class UserIdAdditionalInformation implements TokenEnhancer {
    private final IUserAccountService userAccountService;
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Map<String, Object> info = accessToken.getAdditionalInformation();
        Object principal = authentication.getPrincipal();
        if (principal instanceof SaasUser) {
            String userId = ((SaasUser) principal).getUserId();
            UserAccountBO account = userAccountService.getAccount(userId);
            info.put("userId", userId);
            info.put("email", account.getEmail());
            info.put("phoneNo", account.getPhoneNo());
            info.put("username", account.getUserName());
            info.put("roles", "");
            info.put("type", "");
            info.put("authorities", new ArrayList<>());
            info.put("realName", null);
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
        }
        return accessToken;
    }
}
